package com.cjj2016.cjj.wandoujiaanimationdemo.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.cjj2016.cjj.wandoujiaanimationdemo.R;
import com.cjj2016.cjj.wandoujiaanimationdemo.utils.BigDecimalUtils;

/**
 * Created by CJJ on 2017/1/14.
 */

public class MyLinearLayout extends LinearLayout {
    private static final String TAG = "MyLinearLayout";

    ImageView imageView;
    LinearLayout llContent;
    int llContentWidth;
    int llContentHeight;
    int imageWidth;
    int imageHeight;

    //scrollview的高度
    int mParentScrollViewHeight;

    int mContentMarginTop;

    int mllContentTopOffset;

    int mllContentBottomOffset;

    int mllContentMinBottom;

    boolean mIsAnimation=false; //是否执行动画
    boolean mAnimationEnd =false;//动画结束

    int mImgLeftOffset; //icon图标的left偏移量
    int mImgTopOffset; //icon图标的top偏移量

    ScrollView mParentScrollView;

    //拖拽
    float startY=0;
    int mTouchMoveOffset =0;//拖拽的偏移量

    onUpataBgListener mOnUpdateBgListener;

    onCloseListener mOnCloseListner;

    public MyLinearLayout(Context context) {
        super(context);
    }

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        llContent = (LinearLayout) findViewById(R.id.ll_content_testAct);
        imageView = (ImageView) findViewById(R.id.imageview_ll_content_testAct);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        measureChildren(widthMeasureSpec,heightMeasureSpec);
//        int childNumHeight =0;
//        for(int i=0; i<getChildCount();i++){
//            childNumHeight += getChildAt(i).getMeasuredHeight();
//        }
//        if(childNumHeight > getMeasuredHeight()){
//            setMeasuredDimension(getMeasuredWidth(),childNumHeight);
//        }

        llContentWidth = llContent.getMeasuredWidth();
        llContentHeight = llContent.getMeasuredHeight();

        imageWidth = imageView.getMeasuredWidth();
        imageHeight = imageView.getMeasuredHeight();

        if(mParentScrollView==null){
            mParentScrollView = (ScrollView) getParent();
        }
        mParentScrollViewHeight= mParentScrollView.getMeasuredHeight();
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if( !mIsAnimation){
            //初始化
            int contentTop = mContentMarginTop;
            int contentBottom = contentTop + llContentHeight;
            llContent.layout(0,contentTop,llContentWidth,contentBottom);

//            Log.i(TAG, "onLayout: init exec"+
//                    "left=0;"+
//                    "top="+contentTop+";"+
//                    "right="+llContentWidth+";"+
//                    "bottom="+ contentBottom+";"
//                );
        }else {
            if (mllContentTopOffset == 0) {
                mllContentTopOffset = mContentMarginTop;
            }

            int bottom;
            if( !mAnimationEnd){
                bottom = mllContentMinBottom + mllContentBottomOffset;
            }else {
                //动画结束
                bottom = mllContentTopOffset+llContentHeight + mContentMarginTop;
            }
            llContent.layout(0, mllContentTopOffset + mTouchMoveOffset, llContentWidth, bottom);

            //icon的layout
            if( mImgLeftOffset !=0 && mImgTopOffset !=0){
                int imgright = mImgLeftOffset+imageWidth;
                int imgBottom = mImgTopOffset + imageHeight;
                imageView.layout(mImgLeftOffset,mImgTopOffset, imgright , imgBottom);

//                Log.i(TAG, "onLayout: animation exec"+
//                        "left="+mImgLeftOffset +";" +
//                        "top="+mImgTopOffset+";"+
//                        "right="+imgright+";"+
//                        "bottom="+ imgBottom +";");

            }
        }

    }




    public void InitmContentMarginTop(int marginTop){
        mContentMarginTop= marginTop;

        requestLayout();
    }

    public void setAllViewOffset(int llContentTopOffset,int llcontentBottomOffset,int imgLeftOffset,int imgTopOffset){

        mllContentTopOffset = llContentTopOffset;
        mllContentBottomOffset = llcontentBottomOffset;

        mImgLeftOffset= imgLeftOffset;
        mImgTopOffset = imgTopOffset;

        requestLayout();
    }

    public void setIsAnimation(boolean isAnimation){
        mIsAnimation =isAnimation;
    }

    public void  setmllContentMinBottom(int minBottom){
        mllContentMinBottom = minBottom;
    }

    public void setAnimationEnd(boolean animationEnd){
        mAnimationEnd= animationEnd;
    }

    //向下拖动时，改变llcontent的layout
    public void setTouchMoveOffset(float moveoffset){
        if(moveoffset <0)
            moveoffset=0;
        mTouchMoveOffset = (int) moveoffset;
        requestLayout();
        updateBgColor(mImgLeftOffset);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
         boolean consumption =true;//事件消耗标识

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                startY = event.getY();

                //父节点不处理TouchEvent事件
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                float endY = event.getY();
                float offsetY = endY - startY;

                if( mParentScrollView.getScrollY() <=0 && offsetY >=0){
                    setTouchMoveOffset(offsetY);
                }else {
                    consumption=false;
                    getParent().requestDisallowInterceptTouchEvent(false);
                }

                //Log.i(TAG, "onTouchEvent: offsetY="+offsetY );

                break;
            case MotionEvent.ACTION_UP:
                boolean rebackUp=false;//是否回弹标识

                int animationOffset ;
                if(llContent.getTop() <= mParentScrollViewHeight/2)
                {
                    animationOffset = mTouchMoveOffset;
                    rebackUp =true;
                }else{
                    animationOffset = mParentScrollView.getHeight()-llContent.getTop();
                }

                startAnimat(animationOffset,rebackUp,mTouchMoveOffset);
                break;
        }


        return consumption;
    }



    private void startAnimat(final int animationOffset, final boolean isreback, final int currentMoveOffset) {

        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0,1).setDuration(300);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float ratio = (float) animation.getAnimatedValue();
                if(isreback){
                    mTouchMoveOffset = (int) (animationOffset * (1-ratio));
                }else {
                    mTouchMoveOffset = (int) (animationOffset * ratio)+currentMoveOffset;
                }

                requestLayout();
                updateBgColor(mImgLeftOffset);
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //动画结束
                if( !isreback && mOnCloseListner!=null){
                    mOnCloseListner.onClose();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        valueAnimator.start();
    }



    public void updateBgColor(int offset){
        if(mOnUpdateBgListener !=null){
            float ratio = BigDecimalUtils.divide(offset,mParentScrollViewHeight);
            if(ratio > 1 ) ratio=1;
            if(ratio <0 ) ratio =0;

            mOnUpdateBgListener.onUpdate(ratio);
            Log.i(TAG, "updateBgColor: ratio="+ratio);
        }
    }


    public void  setOnUpdateBgListener(onUpataBgListener listener){
        mOnUpdateBgListener = listener;
    }


    public void  setCloseListener(onCloseListener listener){
        mOnCloseListner = listener;
    }

    //背景更新回调接口
    public  interface  onUpataBgListener{
        void onUpdate(float ratio);
    }

    public interface  onCloseListener{
        void onClose();
    }

}
